package 剑指offer;


import 抽象数据类型.ListNode;

import static 数组和链表.SymbolList.buildList;
import static 数组和链表.SymbolList.printNode;

/**
 * @description:
 * @author: ywk
 * @date: 2020-10-18
 */
public class 删除链表的第n个节点 {
    /**
     * @param head ListNode类
     * @param n    int整型
     * @return ListNode类
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // write code here
        int index = 0;
        ListNode root = new ListNode(Integer.MAX_VALUE);
        root.next = head;
        ListNode preNode = root, currentNode = root, tempNode = root;

        while (index++ < n) {
            currentNode = currentNode.next;
        }
        while (currentNode!= null) {
            tempNode = preNode;
            preNode = preNode.next;
            currentNode = currentNode.next;
        }
        tempNode.next = preNode.next;
        return  root.next;
    }

    public static void main(String[] args) {
        ListNode listNode = buildList(new int[]{1, 2, 3, 4});

        printNode(removeNthFromEnd(listNode, 2));
    }
}
